package cn.gcjxsc.service.task;

import cn.gcjxsc.consts.OrderUtil;
import cn.gcjxsc.entity.mall.BaseOrder;
import cn.gcjxsc.entity.mall.BaseOrder_;
import cn.gcjxsc.entity.mall.WaitForDoneOrderInfo;
import cn.gcjxsc.repository.order.BaseOrderRepository;
import cn.gcjxsc.repository.order.WaitForDoneOrderInfoRepository;
import cn.gcjxsc.repository.specs.OrderSpec;
import cn.gcjxsc.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author pumbaa
 */
@Service
@Slf4j
public class TaskOrderBusiService {
    private static final String KEY = "gcjxsc.key^";
    @Autowired
    private BaseOrderRepository repository;
    @Autowired
    private WaitForDoneOrderInfoRepository wait4doneRepository;

    /**
     * 查询已发货,超时未完成的订单,
     *
     * @param max  最大记录数
     * @param days 天数
     * @return
     */
    public List<BaseOrder> queryUndoneOrder4sending(int max, int days) {
        long times = System.currentTimeMillis()/1000 - 3600*24 * days;
        return repository.queryUncompleteAfter7days(times, max);
    }

    public WaitForDoneOrderInfo convert(BaseOrder order){
        long timestamp = System.currentTimeMillis()/1000;
        WaitForDoneOrderInfo info = new WaitForDoneOrderInfo();
        info.setBusiStatus(0);
        info.setProcessStatus(0);
        info.setLastTime(timestamp);
        info.setOrderNo(order.getSn());
        info.setTimes(0);
        info.setCreated(timestamp);
        info.setDestination("http://wx.gcjxsc.cn/api/task/orderAutoDone");
        return info;
    }

    /**
     * 查询待处理的订单信息
     * @param max 最大记录
     * @return
     */
    public List<WaitForDoneOrderInfo> queryUnprocessOrderInfoList(int max){
        return wait4doneRepository.queryUnprocessOrderInfoList(new PageRequest(0, max));
    }

    @Transactional
    public List<WaitForDoneOrderInfo> save(List<WaitForDoneOrderInfo> entites) {
        return wait4doneRepository.save(entites);
    }

    /**
     * 通知处理业务数据
     * @param data
     * @return
     */
    public String notifyProcessBusiness(WaitForDoneOrderInfo data) {
        String destination = data.getDestination();
        String result = OrderUtil.BusiStatus.FAIL.name().toLowerCase();
        Map<String, String> map = new HashMap<>();

        map.put("orderNo", data.getOrderNo());
        map.put("sign", DigestUtils.md5Hex(data.getOrderNo() + KEY));

        try {
            result = HttpClientUtil.post(destination, map);
        } catch (Exception e) {
            log.error("回调请求失败.[{}], {}", destination, e.getMessage());
        }
        data.setTimes(data.getTimes()+1);
        if (result.equalsIgnoreCase(OrderUtil.BusiStatus.SUCCESS.name())) {
            data.setBusiStatus(OrderUtil.BusiStatus.SUCCESS.getStatus());
            //更新处理状态
        } else {
            //更新请求次数,并将处理状态设置为待通知
            data.setBusiStatus(OrderUtil.BusiStatus.WAIT.getStatus());
            data.setProcessStatus(OrderUtil.QueueStatus.WAIT.getStatus());
        }
        try {
            wait4doneRepository.save(data);
        } catch (Exception e) {
            log.error("更新待通知数据失败.[{}], {}", data.getOrderNo(), e.getMessage());
        }
        return result;
    }
}
